package org.viettan.android.main.io;

import org.viettan.android.main.managers.SettingsManager;

import android.net.Uri;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.inject.Inject;

/**
 * The {@code UrlManager} provides utility methods to create URLs.
 */
public class UrlUtility {

    private final SettingsManager settingsManager;

    @Inject
    UrlUtility(SettingsManager settingsManager) {
	this.settingsManager = settingsManager;
    }

    /**
     * Constructs RSS feed URL back to viettan.org (for the current user language)
     *
     * @param page
     * @return
     */
    private Uri getFeedUrl(String page) {
	return parseUrl("http://www.viettan.org/spip.php?page=" + page + "&lang="
		+ settingsManager.getArticleLanguage());
    }

    /**
     * Returns the "Latest articles" RSS feed.
     */
    public Uri getLatestFeed() {
	return getFeedUrl("applatest");
    }

    /**
     * Returns the RSS feed to the sections.
     */
    public Uri getSectionsFeed() {
	return getFeedUrl("appseclist");
    }

    /**
     * Returns the RSS feed to the "Take Actions".
     */
    public Uri getActionFeed() {
	return getFeedUrl("appact");
    }

    /**
     * Returns the RSS feed for a specific article section.
     */
    public Uri getSectionArticlesFeed(int sectionId) {
	Preconditions.checkArgument(sectionId > 0, "SectionId must be positive");

	return parseUrl("http://www.viettan.org/spip.php?page=appsec&id_rubrique=" + sectionId);
    }

    /**
     * Returns the language-specific podcast URL to Radio CTM.
     */
    public Uri getRadioFeed() {
	return parseUrl("http://www.radiochantroimoi.com/spip.php?page=appradio&lang="
		+ settingsManager.getArticleLanguage());
    }

    /**
     * Returns the full URL to the article XML source.
     *
     * @param articleId
     * @return
     */
    public static Uri getArticleXmlUrl(int articleId) {
	Preconditions.checkArgument(articleId > 0, "ArticleId must be positive");

	return parseUrl("http://www.viettan.org/spip.php?page=appart&id_article=" + articleId);
    }

    /**
     * Parses a string with a URL into an actual {@Code URL}. If the string cannot be parsed,
     * this method will return null.
     *
     * @param url
     *            URL to be parsed
     * @return new instance of {@code URL} or null if it cannot be parsed
     */
    public static Uri parseUrl(String url) {
	if (Strings.isNullOrEmpty(url)) {
	    return null;
	}

	Uri uri = Uri.parse(url);
	// verify again that the parsed URI is correct
	if (Strings.isNullOrEmpty(uri.toString())) {
	    return null;
	}

	return uri;
    }
}
